package com.niiwoo.civet.trade.service.local.configure;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.niiwoo.civet.trade.dao.entity.InvestStdConfig;
import com.niiwoo.civet.trade.dao.mapper.InvestStdConfigMapperExt;
import com.niiwoo.civet.trade.dto.request.creditor.TradableInvestOrderFilterRequestDTO;
import com.niiwoo.civet.trade.dto.response.RelationInvestStdConfigDTO;
import com.niiwoo.civet.trade.dto.response.RelationInvestStdConfigItemDTO;

@Service
public class InvestStdConfigLocalService {

    @Autowired
    private InvestStdConfigMapperExt investStdConfigMapperExt;

    public List<InvestStdConfig> selectByProductTypeAndConfigType(Byte productType, Byte configType) {
    	return investStdConfigMapperExt.selectByProductTypeAndConfigType(productType, configType);
    }
    
    public List<InvestStdConfig> selectByProductType(Byte productType) {
    	return investStdConfigMapperExt.selectByProductType(productType);
    }
    
    public List<RelationInvestStdConfigItemDTO> selectByRelationAndProductType(Byte productType) {
    	return investStdConfigMapperExt.selectByRelationAndProductType(productType);
    }
    
    /**
     * 级联方式获取筛选配置，configType=null则取所有
     * @param productType
     * @param configType
     * @return
     */
    public List<InvestStdConfig> selectByRelationAndConfigType(TradableInvestOrderFilterRequestDTO request) {
    	return investStdConfigMapperExt.selectByRelationAndConfigType(request);
    }
    
    public List<RelationInvestStdConfigDTO> findRelationConfigByProductType(Byte productType) {
    	List<RelationInvestStdConfigItemDTO> items = investStdConfigMapperExt.selectByRelationAndProductType(productType);
    	
    	if (items == null || items.isEmpty()) return null;
    	
    	List<RelationInvestStdConfigItemDTO> tmp = null;
    	Map<String, List<RelationInvestStdConfigItemDTO>> relationConfigs = new HashMap<>();
    	for (RelationInvestStdConfigItemDTO item : items) {
    		if (relationConfigs.containsKey(String.valueOf(item.getRelationConfigId())))
				tmp = relationConfigs.get(String.valueOf(item.getRelationConfigId()));
    		else 
    			tmp = new ArrayList<>();
    		
    		tmp.add(item);
    		relationConfigs.put(String.valueOf(item.getRelationConfigId()), tmp);
    	}

    	List<RelationInvestStdConfigDTO> result = new ArrayList<>();
    	Iterator<String> it = relationConfigs.keySet().iterator();
    	while (it.hasNext()) {
    		result.add(new RelationInvestStdConfigDTO(relationConfigs.get(it.next())));
    	}
    	
    	return result;
    }
}
